package com.wysiwyg.common.web.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.wysiwyg.common.constant.AuthConstant;
import com.wysiwyg.common.context.ContextUser;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashSet;
import java.util.Set;

/**
 * @author wwcc
 * @date 2024/12/16 21:10:08
 */
@Component
public class UserContextFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest httpServletRequest) {
            processUserInfo(httpServletRequest);
        }

        try {
            chain.doFilter(request, response);
        } finally {
            ContextUser.clear();
        }
    }

    /**
     * 处理用户信息，从请求头中提取并设置到ThreadLocal
     */
    private void processUserInfo(HttpServletRequest request) {
        String userInfoStr = request.getHeader(AuthConstant.HEAD_USER_INFO);
        if (StrUtil.isBlank(userInfoStr)) {
            return;
        }

        try {
            String jsonStr = decodeBase64String(userInfoStr);
            JSONObject userInfoJson = JSON.parseObject(jsonStr);
            
            String userId = userInfoJson.getString("id");
            String userName = userInfoJson.getString("username");
            String roles = userInfoJson.getString("roles");

            if (userId != null && userName != null) {
                Set<String> roleSet = parseRoles(roles);
                ContextUser.setUserInfo(userId, userName, roleSet);
            }
        } catch (Exception e) {
            // 记录日志但不中断请求流程
            System.err.println("用户信息解析失败: " + e.getMessage());
        }
    }

    /**
     * 解析角色信息
     */
    private Set<String> parseRoles(String roles) {
        if (StrUtil.isBlank(roles)) {
            return null;
        }
        return new HashSet<>(JSON.parseArray(roles, String.class));
    }


    /**
     * 将Base64编码的用户信息字符串解码为UTF-8编码的JSON字符串
     *
     * @param base64Str Base64编码的用户信息字符串
     * @return 解码后的UTF-8格式JSON字符串
     * @throws IllegalArgumentException 如果输入的Base64字符串格式无效
     */
    private static String decodeBase64String(String base64Str) {
        // 对Base64编码的字符串进行解码
        byte[] userNameBytes = Base64.getDecoder().decode(base64Str);
        // 将解码后的字节数组转换为UTF-8编码的字符串
        String jsonStr = new String(userNameBytes, StandardCharsets.UTF_8);
        // 返回解析后的JSON字符串
        return jsonStr;
    }
}